package de.herberlin.webapp.core;

import java.io.IOException;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * ConfigurationService.java
 *
 * Created on 26. November 2006, 22:00
 *
 * @author herberlin
 *
 */
public class Configuration {
    
    
    public static final String SETTING_TEST_MODE="test.mode";
    
    
    private String configFileName="/application.properties";
    private static Configuration _instance=null;
    private Properties props=new Properties();
    private Context env=null;
    private Log logger=LogFactory.getLog(getClass());
    
    private Configuration() {
        try {
            props.load(getClass().getResourceAsStream(configFileName));
            logger.debug("Configuration loaded: "+props);
            testMode=new Boolean("true").equals(getSetting(SETTING_TEST_MODE));
            logger.info("TestMode="+testMode);
        } catch (IOException ex) {
            logger.error("Error loading configuration.",ex);
        }
    }
    
    public static Configuration getInstance(){
        
        if (_instance==null) {
            _instance=new Configuration();
        }
        return _instance;
    }
    
    public String getSetting(String name) {
        String st= props.getProperty(name);
    	logger.debug(name +" => "+st);
    	return st;

    }
    
    public String getSetting(Class cl,String name) {
    	return getSetting(cl.getName()+"."+name);
    }
    
    public Integer getIntSetting(String name) {
        String st=getSetting(name);
        if (st==null) {
        	return null;
        } else {
            try {
                return Integer.parseInt(st);
            } catch (NumberFormatException ex) {
                throw new AppException("Can't parse setting "+name + " to integer.",ex);
            }
        }
    }
    
    
    private static  boolean testMode=false;
    public static boolean isTestMode() {
        
        return testMode;
        
    }
    
    
    public String getEnvEntry(String key) {
        try {
            if (env==null) {
                env=(Context)new InitialContext().lookup("java:comp/env");
            }
            return  (String) env.lookup(key);
        } catch (Exception e) {
            logger.equals(e);
            throw new AppException(e);
        }
    }
}
